package com.roc.web.action.merinfo;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.merinfo.MerInfoImportBatchService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/mer")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MerInfoBatchImportAction extends BaseAction{
	private static Logger log = LogManager.getLogger(MerInfoBatchImportAction.class);
	
	private File upload;
	
	private InputStream excelFile;
	
	private InputStream downloadFile;
	
	private String imporNum;
	
	@Autowired
	private IExcelService excelService;
	
	@Autowired
	private MerInfoImportBatchService merInfoImportBatchService;
	/**
	 * 商户批导页面初始化
	 * @return
	 */
	@Action(value="merInfoBatchImportInit",results={@Result(name="success",location="/pages/merinfo/merinfoBatchImport.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String merInfoBatchImportInit(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		 if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		return SUCCESS;
	}
	
	/**
	 * 商户批量导入
	 * @return
	 */
	@Action(value = "merInfoBatchImport", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(location = "/pages/merinfo/merinfoBatchImport.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp"),
			@Result(name ="noImportedDealRs", type = "chain", location = "noImportedDeal")})
	public String merInfoBatchImport(){
		Operators oper = (Operators) ActionContext.getContext().getSession().get(
				Constant.SESSION_LOGIN_MERCHANT);
		 if(oper.getRoleType().equals(Role.AGENT.getCode()) && !oper.getAccountNo().equals("sdsyb")){
			 addActionError("无权限访问");
			 return ERROR;
		 }
		try {
			Map<String ,Object> resultMap = merInfoImportBatchService.merInfoImportToDB(upload, oper,imporNum);
			List<List<Object>> noImportList = (List<List<Object>>) resultMap.get("noImportedList");
			if(noImportList != null && noImportList.size()>0){
				log.info("开始导出成功导入数据，共计：【"+noImportList.size()+"】条");
				getRequest().setAttribute("resultMap", resultMap);
				return "noImportedDealRs";
			}
			if((Boolean) resultMap.get("importedFlag")){
				addActionError("操作成功，"+resultMap.get("msg").toString());
			}else{
				addActionError("操作失败，"+resultMap.get("msg").toString());
			}
			
		} catch (Exception e) {
			log.error("商户信息批量导入异常："+e.getMessage());
			addActionError(e.getCause().getMessage());
//			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 未成功导出数据存入excel
	 * @return
	 */
	@Action(value="noImportedDeal",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/merinfoBatchImport.jsp")})
	public String noImportedDeal(){
		try {
			Map<String,Object> resultMap = (Map<String, Object>) getRequest().getAttribute("resultMap");
			HSSFWorkbook work=excelService.exportNoImportedMerList(resultMap);

			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();
		} catch (Exception e) {
			log.error("导出成功导入的商户信息失败"+e.getMessage());
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 模板下载
	 * @return
	 */
	@Action(value="downloadModel",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/octet-stream", "inputName",  
			            "downloadFile","contentDisposition",  "attachment;filename=${downloadName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/merinfoBatchImport.jsp") })
	public String downloadModel(){
		try {
			log.info("批导模板下载");
		} catch (Exception e) {
			log.error("导出商户批导模板失败"+e.getMessage());
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public String getExcelName() {
		String excelName="成功导入商户信息"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				log.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	
	public String getDownloadName(){
		String downloadName="商户批导模板";
		 
		try {
			downloadName = new String(downloadName.getBytes(),"ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("生成excel名称失败了！");
		}
	 
	return  downloadName;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public InputStream getDownloadFile() {
		return ServletActionContext.getServletContext().getResourceAsStream("/model/batchImportMerInfo.xlsx");  
	}

	public void setDownloadFile(InputStream downloadFile) {
		this.downloadFile = downloadFile;
	}

	public String getImporNum() {
		return imporNum;
	}

	public void setImporNum(String imporNum) {
		this.imporNum = imporNum;
	}
	
	
	
	
}
